import {
    successEl,
    restartEl,
    againEl,
    nextEl,
    maskEl,
    allCardEl,
    cardWidth,
    cardHeight,
    pageWidth,
    bottomEl,
    pageHeight,
    openArray,
    sureEl,
    continueEl,
    cancleEl,
    submitEl,
    exchangeEl,
    topOpenArr,
    coinsEl,
    checkEl,
    hideEl,
    stateEl,
    nextCheckEl,
    pointEl,
    coinContentEl,
    backEl,
    containerEl
}
from './varible.js';
import {
    delPx,
    numberToCard
} from './method.js';
import {
    loadGame
} from './load.js';
import {
    addTableCard
} from './addTable.js';

let userArr = new Array();
let timeArr = new Array();
let cardArray = new Array();
let saveArr = new Array();
let sTime = 0;
let totalTime = 0;
let length = 5;
let coverLength;
let blIndex = 0;
let lineIndex;
let nArray = 0;
let top_list;
let divList;
//顶部桌牌区的点击事件
function topClickEvent(array, topCardLength, userArray, timeArray, startTime, cardFirst, bfIndex, aov_list) {
    top_list = aov_list;
    if (Number.isInteger(bfIndex)) {
        lineIndex = bfIndex;
    }
    if (nArray == 0) {
        nArray = array;
    }
    console.log(nArray);
    sTime = startTime;
    let topCardNum = topCardLength;
    divList = document.querySelectorAll(".pic");
    let openList = document.querySelectorAll(".openPic");
    for (let i = 0; i < divList.length; i++) {
        divList[i].addEventListener('click', function () {
            let number = parseInt(divList[i].getAttribute("number"));
            let index = parseInt(divList[i].getAttribute("index"));
            //此处需判断一下点击的牌是否是掀开的牌
            if (array[index][6] == 0) {
                for (let k = 0; k < openArray.length; k++) {
                    if ((openArray[k] == (number - 1)) || (openArray[k] == (number + 1)) || (openArray[k] == 13 && number == 1) || (openArray[k] == 1 && number == 13) || (document.querySelector(".openPic").getAttribute("type") == "all")) {
                        // console.log("topOpenArr" + topOpenArr);
                        for (let m = 0; m < topOpenArr.length; m++) {
                            if (topOpenArr[m] == number) {
                                topOpenArr.splice(m, 1);
                                break;
                            }
                        }
                        //记录时间
                        let endTime = new Date();
                        if (timeArr.length == 0) {
                            cardArray.push(parseInt(cardFirst));
                            userArr.push(parseInt(bfIndex));
                            timeArr.push(0);
                            cardArray.push(parseInt(divList[i].getAttribute("number")));
                            timeArray.push(parseInt((endTime - startTime) / 1000));
                            timeArr.push(parseInt((endTime - startTime) / 1000));
                            totalTime += parseInt((endTime - startTime) / 1000);
                        } else {
                            cardArray.push(parseInt(divList[i].getAttribute("number")));
                            timeArray.push(parseInt((endTime - startTime) / 1000) - totalTime);
                            timeArr.push(parseInt((endTime - startTime) / 1000) - totalTime);
                            totalTime += (parseInt((endTime - startTime) / 1000) - totalTime);
                        }
                        //记录用户操作
                        userArray.push(index);
                        userArr.push(index);
                        topCardNum--;

                        //此处需将对应子节点的父节点数-1
                        for (let n = 7; n <= 10; n++) {
                            if (array[index][n] == -1) {
                                break;
                            } else {
                                if (array[array[index][n]][6] > 0) {
                                    array[array[index][n]][6]--;
                                    if (array[array[index][n]][6] == 0) {
                                        let num = divList[array[index][n]].getAttribute("number");
                                        //如果此牌无父节点则自动翻面
                                        divList[array[index][n]].style.backgroundPosition = numberToCard(num, 0);
                                        topOpenArr.push(parseInt(num));
                                    }
                                }
                            }
                        }

                        // divList[i].className = "openPic";
                        // divList[i].style.zIndex = openArray.length;
                        // openArray.push(parseInt(divList[i].getAttribute("number")));
                        saveArr.push(openArray[0]);
                        openArray[0] = parseInt(divList[i].getAttribute("number"));
                        divList[i].style.display = "none";
                        let openEl = document.querySelector(".openPic");
                        openEl.setAttribute("number", divList[i].getAttribute("number"));
                        openEl.setAttribute("type", divList[i].getAttribute("type"));
                        openEl.setAttribute("color", divList[i].getAttribute("color"));
                        openEl.setAttribute("decor", divList[i].getAttribute("decor"));
                        openEl.setAttribute("index", divList[i].getAttribute("index"));
                        openEl.style.backgroundPosition = numberToCard(openArray[0], 0);
                        // divList[i].style.left = parseInt(delPx(openList[0].style.left)) + "px";
                        // divList[i].style.top = parseInt(delPx(openList[0].style.top)) + "px";
                        bottomEl.appendChild(divList[i]);
                        //如果牌桌区无牌游戏胜利
                        if (topCardNum == 0) {
                            console.log("选择顺序", userArr);
                            console.log("花费时间", timeArr);
                            console.log("纸牌顺序", cardArray);
                            let storage = window.localStorage;
                            let coins = parseInt(storage.getItem("coins")) + 100;
                            storage.setItem("coins", coins);
                            // let check = storage.getItem("check");
                            // storage.setItem(check, JSON.stringify({
                            //     "seq_list": userArray,
                            //     "time_list": timeArray,
                            //     "is_finish": 1
                            // }));
                            successEl.style.display = 'block';
                        } else if (coverLength < 0) {
                            let flag = 0;
                            for (let n = 0; n < topOpenArr.length; n++) {
                                for (let p = 0; p < openArray.length; p++) {
                                    if ((openArray[p] == (topOpenArr[n] - 1)) || (openArray[p] == (topOpenArr[n] + 1)) || (openArray[p] == 13 && topOpenArr[n] == 1) || (openArray[p] == 1 && topOpenArr[n] == 13)) {
                                        flag = 1;
                                        break;
                                    }
                                }
                                if (flag == 1) {
                                    break;
                                }
                            }
                            if (flag == 0) {
                                // alert("纸牌区无可回收纸牌，无法继续游戏");
                                continueEl.style.display = "block";
                                if (parseInt(window.localStorage.getItem("coins")) <= 0) {
                                    coinContentEl.innerHTML = "您已没有金币，无法进行纸牌的兑换";
                                    exchangeEl.style.display = "none";
                                }
                            }
                        }
                        break;
                    }

                }
                //如果被点击的掀开纸牌符合条件就定位到下面的牌区
                //divList[i].style.backgroundPosition = (number - 1) * -80 + "px 0px";
                // console.log("父节点", array[index][2], array[index][3], "父节点个数", array[index][6], "子节点", array[index][7], array[index][8]);
            };
        })
    }
}
//底部未掀开牌的点击事件

function bottomClickEvent(blastIndex, userArray, cardFirst, bfIndex, array, aov_list) {
    if (nArray == 0) {
        nArray = array;
    }

    top_list = aov_list;
    console.log("aov_list", aov_list);
    console.log("top_list", top_list);
    // console.log("nArray", nArray);
    if (Number.isInteger(bfIndex)) {
        lineIndex = bfIndex;
    }
    console.log(bfIndex);
    let divList = document.querySelectorAll(".picBtm");
    // let openCard = document.querySelector(".openPic");
    coverLength = divList.length - 1;
    for (let i = 0; i < divList.length; i++) {
        divList[i].addEventListener('click', function () {
            let bCardNum = document.querySelector(".bCardLength");
            bCardNum.innerHTML = coverLength;
            //将桌牌区下来的牌隐藏掉
            let openLists = document.querySelectorAll(".openPic");
            for (let k = 0; k < openLists.length - 1; k++) {
                openLists[k].style.display = "none";
            }
            let openCard = document.querySelector(".openPic");
            saveArr.push(openArray[0]);
            openArray[0] = (parseInt(divList[coverLength].getAttribute("number")));
            // openCard.style.backgroundPosition = numberToCard(openArray[0], 0);
            //记录时间
            let endTime = new Date();
            if (timeArr.length == 0) {
                cardArray.push(parseInt(cardFirst));
                userArr.push(parseInt(bfIndex));
                timeArr.push(0);
                cardArray.push(parseInt(divList[i].getAttribute("number")));
                timeArr.push(parseInt((endTime - sTime) / 1000));
                totalTime += parseInt((endTime - sTime) / 1000);
            } else {
                cardArray.push(parseInt(divList[i].getAttribute("number")));
                timeArr.push(parseInt((endTime - sTime) / 1000) - totalTime);
                totalTime += (parseInt((endTime - sTime) / 1000) - totalTime);
            }
            //记录用户操作
            userArr.push(parseInt(divList[i].getAttribute("index")));
            //万能纸牌
            if (divList[i].getAttribute("type") == "all") {
                allCardEl.style.display = "block";
                openLists[openLists.length - 1].style.backgroundPosition = "0 " + cardHeight * 6 + "px";
            } else {
                openLists[openLists.length - 1].style.backgroundPosition = numberToCard(openArray[0], 0);

            }
            openLists[openLists.length - 1].setAttribute("type", divList[i].getAttribute("type"));
            openCard.setAttribute("number", openArray[0]);
            divList[coverLength].style.display = "none";
            divList[coverLength].className = "";
            coverLength--;
            if (coverLength < 0) {
                let flag = 0;
                for (let n = 0; n < topOpenArr.length; n++) {
                    for (let p = 0; p < openArray.length; p++) {
                        if ((openArray[p] == (topOpenArr[n] - 1)) || (openArray[p] == (topOpenArr[n] + 1)) || (openArray[p] == 13 && topOpenArr[n] == 1) || (openArray[p] == 1 && topOpenArr[n] == 13) || (openLists[openLists.length - 1].getAttribute("type") == "all")) {
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1) {
                        break;
                    }
                }
                if (flag == 0) {
                    // console.log("纸牌区无可回收纸牌，无法继续游戏");
                    continueEl.style.display = "block";
                    if (parseInt(window.localStorage.getItem("coins")) <= 0) {
                        coinContentEl.innerHTML = "您已没有金币，无法进行纸牌的兑换";
                        exchangeEl.style.display = "none";
                    }
                }
            }
        })
    }
}
//游戏点击按钮的事件
function gameOver() {
    backEl.addEventListener('click', function () {
        console.log(top_list);
        //撤回对桌牌区的操作
        if (userArr[userArr.length - 1] < lineIndex) {
            let index = userArr[userArr.length - 1];
            
            let divEl = addTableCard(top_list[nArray[index][13]][nArray[index][11]][nArray[index][12]], nArray, top_list.length);
            containerEl.appendChild(divEl);
        }
    });
    restartEl.addEventListener('click', function () {
        gameAgain();
    });
    pointEl.addEventListener('click', function () {
        stateEl.style.display = "block";
    });
    againEl.addEventListener('click', function () {
        gameAgain();
    });
    //隐藏游戏提示
    hideEl.addEventListener('click', function () {
        stateEl.style.display = "none";
        let storage = window.localStorage;
        storage.setItem("state", "1");
    })
    nextEl.addEventListener('click', function () {
        successEl.style.display = 'none';
        let storage = window.localStorage;
        let currentCheck = storage.getItem("check");
        storage.setItem(currentCheck, JSON.stringify({
            "seq_list": userArr,
            "time_list": timeArr,
            "card_list": cardArray,
            "is_finish": 1
        }));
        nextCheck();

    });
    nextCheckEl.addEventListener('click', function () {
        continueEl.style.display = "none";
        let storage = window.localStorage;
        let currentCheck = storage.getItem("check");
        storage.setItem(currentCheck, JSON.stringify({
            "seq_list": userArr,
            "time_list": timeArr,
            "card_list": cardArray,
            "is_finish": 0
        }));
        nextCheck();
    })
    sureEl.addEventListener('click', function () {
        allCardEl.style.display = "none";
    });
    cancleEl.addEventListener('click', function () {
        continueEl.style.display = "none";
        gameAgain();
    });
    exchangeEl.addEventListener('click', function () {
        console.log(cardArray);
        let storage = window.localStorage;
        continueEl.style.display = "none";
        if (parseInt(storage.getItem("coins")) < 100) {
            alert("您已没有金币，无法再兑换纸牌");
        } else {
            let coins = parseInt(storage.getItem("coins")) - 100;
            storage.setItem("coins", coins);
            coinsEl.innerHTML = coins;
        }
        //前端随机向纸牌区添加五张牌
        for (let i = 0; i < 5; i++) {
            let num = Math.floor(Math.random() * 13) + 1;
            let divEl = document.createElement("div");
            divEl.setAttribute("number", num);
            console.log("blIndex", blIndex);
            divEl.setAttribute("index", blIndex + length - i);
            divEl.setAttribute("type", "");
            divEl.setAttribute("color", "");
            divEl.setAttribute("decor", "");
            divEl.className = "picBtm";
            divEl.style.zIndex = i + 1;
            divEl.style.backgroundPosition = "0px " + cardHeight * 6 + "px";
            divEl.style.left = (i * 2 + 40) + 'px';
            divEl.style.top = 20 + 'px';
            document.querySelector(".bCardLength").innerHTML = 5;
            bottomEl.appendChild(divEl);
            if (i == 4) {
                length += 5;
                // blIndex += 5;
            }
        }
        bottomClickEvent(openArray);

    });
    //点击提交游戏数据给后端
    submitEl.addEventListener('click', function () {
        //获得缓存的游戏数据提交给后端，提交成功后alert
        let storage = window.localStorage;
        let student_id = storage.getItem("studentId");
        let json = {
            "stuid": student_id,
        };
        for (let i = 1;; i++) {
            if (storage.getItem(i) != null) {
                console.log(storage.getItem(i));
                json[i] = JSON.parse(storage.getItem(i));
            } else {
                break;
            }
        }
        console.log(json);
        // $.ajax({
        //     type: 'POST',
        //     url: '../static/jsons/1/1.json',
        //     data: JSON.stringify(json),
        //     dataType: "json",
        //     success: function (data) {
        //         alert("提交成功！");
        //     },
        //     error: function () {
        //         alert("提交失败！");
        //     }
        // })
        axios.post("", JSON.stringify(json)).then(function (response) {
            console.log(response);
            alert("提交成功");
        }, function (err) {
            alert("提交失败");
        });
    })
}

function gameAgain() {
    let storage = window.localStorage;
    successEl.style.display = 'none';
    window.location.reload();
    maskEl.style.display = "none";
}

function nextCheck() {
    coinContentEl.innerHTML = "您当前已无法回收桌牌区的任意纸牌，是否选择耗100金币随机兑换5张纸牌？";
    console.log(timeArr, userArr);
    let storage = window.localStorage;
    let currentCheck = storage.getItem("check");
    let nextCheck = parseInt(currentCheck.split(".")[0]) + 1;
    if (nextCheck > 10) {
        alert("您已闯过所有关卡！");
        let student_id = storage.getItem("studentId");
        let json = {
            "stuid": student_id,
        };
        for (let i = 1;; i++) {
            if (storage.getItem(i) != null) {
                console.log(storage.getItem(i));
                json[i] = JSON.parse(storage.getItem(i));
            } else {
                break;
            }
        }
        console.log(json);
        axios.post("", JSON.stringify(json)).then(function (response) {
            console.log(response);
            alert("提交成功");
            window.localStorage.clear();
            gameAgain();
        }, function (err) {
            alert("提交失败");
        });
        // window.localStorage.clear();
        // gameAgain();
    } else {
        storage.setItem("check", nextCheck);
        // console.log(nextCheck);
        // loadGame(nextCheck);
        gameAgain();
    }
}
export {
    topClickEvent,
    bottomClickEvent,
    gameOver
}